import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import viteEslint from 'vite-plugin-eslint';
import viteCompression from 'vite-plugin-compression';
import { visualizer } from 'rollup-plugin-visualizer';
import autoImport from 'unplugin-auto-import/vite';
import autoImportComponents from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import { resolve } from 'path';
import { ElementPlusExtensionResolver } from './src/plugins/ui/elementPlusExtensionResolver';

export default defineConfig({
  resolve: {
    alias: {
      '@': resolve(__dirname, './src')
    }
  },
  plugins: [
    vue(),
    vueJsx(),
    autoImport({
      imports: [
        'vue',
        'vue-router',
        {
          from: 'vue-router',
          imports: [
            'RouteLocationRaw',
            'RouteRecordRaw',
            'RouteLocationNormalized',
            'RouteLocationNormalizedLoaded',
            'RouteRecordNormalized',
            'RouteRecordRaw'
          ],
          type: true
        }
      ],
      resolvers: [ElementPlusResolver()],
      dts: 'src/auto-import.d.ts',
      eslintrc: {
        enabled: true,
        filepath: resolve(__dirname, './.eslintrc-auto-import.json'),
        globalsPropValue: true
      }
    }),
    autoImportComponents({
      dts: 'src/components.d.ts',
      resolvers: [ElementPlusResolver({ importStyle: false }), ElementPlusExtensionResolver()]
    }),
    viteCompression(),
    viteEslint({
      include: ['/src/**/*.vue', '/src/**/*.ts'],
      exclude: ['node_modules'],
      cache: false
    }),
    visualizer({
      open: true,
      filename: 'visualizer.html'
    })
  ],
  build: {
    outDir: 'dist',
    minify: 'esbuild',
    sourcemap: false,
    emptyOutDir: true,
    modulePreload: true,
    chunkSizeWarningLimit: 1500,
    rollupOptions: {
      output: {
        entryFileNames: `app/[name]-[hash].js`,
        chunkFileNames: `js/[name].${Date.now()}.js`,
        manualChunks(id) {
          if (id.includes('node_modules')) {
            const idStr = id.toString().slice(id.lastIndexOf('node_modules/'), id.toString().length);
            const arr = idStr.split('node_modules/')[1].split('/');
            switch (arr[0]) {
              case '@vue':
              case '@vueuse':
              case 'element-plus-extension':
              case 'element-plus':
              case '@element-plus':
              case 'lodash-es':
              case 'echarts':
                return `_${arr[0]}`;
              default:
                return '__vendor';
            }
          }
        }
      }
    }
  }
});
